//封装购物车模块
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI , getCartListAPI, deleteCartAPI} from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {

  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  //1.定义state - cartList
  const cartList = ref([])

  //获取最新购物车列表
  const updateNewList = async() => {
      const res = await getCartListAPI()
      cartList.value = res.result
  }

  //2.定义action - addCart
  const addCart = async(goods) => {
    //判断是否登录
    if(isLogin){
      const { skuId, count } = goods
      //加入购物车
      await insertCartAPI({skuId, count})
      //获取最新购物车列表
      updateNewList()
    }
    else{
      //添加购物车操作:判断当前添加的元素在购物车中是否存在
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      //已添加过：count+1
      if (item) {
        item.count += goods.count
      }
      //未添加过：直接push
      else {
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车
  const delCart = async(skuId) => {
    if(isLogin){
      await deleteCartAPI([skuId])
      updateNewList()
    }
    else{
      //思路：
      //1. 找到想要删除的元素下标-> splice
      const idX = cartList.value.findIndex((item) => item.skuId === skuId)
      cartList.value.splice(idX, 1)
      //2. 使用数组过滤方法-> filter
      //cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
    }
  }

  //清除本地购物车
  const clearCart = () => {
    cartList.value = []
  }

  //单选功能
  const singleChange = (skuId, selected) => {
    // 通过skuId找到对应项
    const item = cartList.value.find((item) => item.skuId === skuId)
    // 然后修改selected
    item.selected = selected
  }

  //多选功能
  const allChange = (selected) => {
    // 点击全选，每一项设置成selected状态
    cartList.value.forEach(item => item.selected = selected)
  }

  // 计算属性
  //1.总的数量 所有项的count之和
  const totalCount = computed(() => {
    return cartList.value.reduce((a,c)=>a + c.count, 0)
  })
  //2.总价格 所有项的count * price之和
  const totalPrice = computed(() => {
     return cartList.value.reduce((a,c)=>a + c.count * c.price, 0)
  })

  //3.多选功能：是否全选
  const isAll = computed(() => {
   return cartList.value.every((item) => item.selected)
  })

  //4.已选数量
  const selectedCount = computed(() => {
    return cartList.value.filter(item => item.selected)
                          .reduce((a,c) => a + c.count, 0)
  })

  //5.已选价格
  const selectedPrice = computed(() => {
    return cartList.value.filter(item => item.selected)
                          .reduce((a,c) => a + c.count * c.price, 0)
  })

  return {
    cartList,
    addCart,
    delCart,
    clearCart,
    singleChange,
    allChange,
    totalCount,
    totalPrice,
    isAll,
    selectedCount,
    selectedPrice,
    updateNewList
  }
}, {
    persist: true
})
